#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "utils/win32util.h"
#include  "QDebug"
#include "QEvent"
#include "event/logevent.h"
#include "QApplication"
#include "QTimer"
#include "opencv2/core.hpp"
#include "utils/imghelper.h"
#include "QThread"
#include "utils/deviceutils.h"
#include "httpclient.h"
#include "QDateTime"
#include "QMessageBox"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    initView();
    initData();
    registerHotKey();

    gameTask = new GameTask(this);
    gamePersent = new GamePersent(this);
    connect(bindGame, &QPushButton::clicked ,this, [=](){
        gamePersent->bindGame(TLBB_GAME_CLASS_NAME);
        if(GameManager::getInstantce()->roleTask == ROLE_TASK_NORMAL){
            setButtonEnable(ROLE_TASK_NORMAL, gamePersent->isBindGame);
        }
    });

    connect(btnTaskExpand, &QPushButton::clicked,this, [&](){
        taskKuoZhang();
    });

}

bool MainWindow::event(QEvent *event){
    if(event->type() == QEvent::User + 0xFF){
        LogEvent* logEvent = (LogEvent*)event;
        tvLog->append(logEvent->getLog());
        return false;
    }
    return QMainWindow::event(event);
}

void MainWindow::initView(){
    ui->groupBox_6->setHidden(true);

    tvLog = ui->tvLog;
    bindGame = ui->bindGame;
    statusBar = ui->statusBar;
    leImgDiscern = ui->le_img_discern;

    //复活
    btnHell_ly = ui->btn_hell_ly;
    btnHell_dl = ui->btn_hell_dl;
    btnHell_sz = ui->btn_hell_sz;
    btnHell_dhgz = ui->btn_hell_dhgz;

    btnRunMerchant = ui->btn_runMerchant;
    connect(btnRunMerchant, &QPushButton::clicked,this, [&](){
        taskRunshop(btnRunMerchant, GameManager::RunStatue::StateGoGroup, ROLE_TASK_SHOP);
    });

    btnRunRemote = ui->btn_runRemote;
    connect(btnRunRemote, &QPushButton::clicked,this,[&](){
        taskRunshop(btnRunRemote, GameManager::RunStatue::StateLeave, ROLE_TASK_SHOP_REMOTE);
    });

    btnRunGroup = ui->btn_runGroup;
    connect(btnRunGroup, &QPushButton::clicked,this,[&](){
        taskRunshop(btnRunGroup, GameManager::RunStatue::StateBack, ROLE_TASK_SHOP_BACK);
    });

    btnTaskZhongZhi = ui->btn_taskZhongZhi;
    connect(btnTaskZhongZhi, &QPushButton::clicked,this,[&](){
        taskZhongZhi();
    });

    //按键映射
    leBloodKey = ui->le_bloodKey;
    leMagicKey = ui->le_magicKey;
    leSkill = ui->le_skill;
    leSkill2 = ui->le_skill2;
    leSpeed = ui->le_speed;

    //保存配置
    btnSaveSetting = ui->btn_saveSetting;
    tbRole = ui->tb_role;
    tbRole->init();

    runshopTable = ui->runshop_table;
    runshopTable->init();

    btnTaskExpand = ui->btn_taskExpand;
    kuozhangTable = ui->kuozhang_table;
    kuozhangTable->init();


    zhongZhiTable = ui->zhongzhi_table;
    zhongZhiTable->init();
}
void MainWindow::initData()
{
    //初始化复活数据
    QString outHellCity = Setting::getInstance()->getOutHellCity();
    if(outHellCity == HELL_LY){
        btnHell_ly->setChecked(true);
    }else if(outHellCity == HELL_DL){
        btnHell_dl->setChecked(true);
    }else if(outHellCity == HELL_SZ){
        btnHell_sz->setChecked(true);
    }else if(outHellCity == HELL_DHGZ){
        btnHell_dhgz->setChecked(true);
    }

    //加血、加蓝
    leBloodKey->setText(Setting::getInstance()->getBloodKey());
    leMagicKey->setText(Setting::getInstance()->getMagicKey());
    leSkill->setText(Setting::getInstance()->getSkill());
    leSkill2->setText(Setting::getInstance()->getSkill2());
    leSpeed->setText(Setting::getInstance()->getSpeed());

    //设置状态栏 卡密剩余时长
    QDateTime::fromString( "yyyy-MM-dd hh:mm").toString();
    float invalidTime = GameManager::getInstantce()->invalidTime / 1000.0f / 60.0f /60.0f /24.0f;
    statusBar->showMessage(QString("当前版本号:%1 卡密剩余时长:%2天").arg(VERSION).arg(QString::number(invalidTime,'f', 1)));

    connect(tbRole, &RoleTableWidget::logEvent, this,[&](QString log){
        tvLog->append(log);
        QMessageBox::warning(this,"系统提示", log,QMessageBox::Ok);
    });

    //关联runshopTableWidget中的日志
    connect(runshopTable, &RunshopTableWidget::logEvent, this,[&](QString log){
        tvLog->append(log);
        QMessageBox::warning(this,"系统提示", log,QMessageBox::Ok);
    });
    leImgDiscern->setText(QString::number(Setting::getInstance()->getImgDiscern()));
}

void MainWindow::registerHotKey()
{
    cancelTaskKey = new QxtGlobalShortcut(this);
    if(cancelTaskKey->setShortcut(QKeySequence("Ctrl+Q"))){
        connect(cancelTaskKey, &QxtGlobalShortcut::activated,[=]() {
            this->close();
        });
    }
}

MainWindow::~MainWindow()
{
    if(gamePersent != nullptr){
        delete gamePersent;
        gamePersent = nullptr;
    }
    delete ui;
    if(gameTask != nullptr){
        delete gameTask;
        gameTask = nullptr;
    }

    if(runShop != nullptr){
        GameManager::getInstantce()->roleTask = ROLE_TASK_NORMAL;
        delete runShop;
        runShop = nullptr;
    }

    if(cancelTaskKey != nullptr){
        delete  cancelTaskKey;
        cancelTaskKey = nullptr;
    }

    if(allRunShopBeans != nullptr){
        qDeleteAll(allRunShopBeans->begin(), allRunShopBeans->end());
        allRunShopBeans->clear();
        delete  allRunShopBeans;
    }

    if(allZhongZhiBeans != nullptr){
        qDeleteAll(allZhongZhiBeans->begin(), allZhongZhiBeans->end());
        allZhongZhiBeans->clear();
        delete allZhongZhiBeans;
    }
}

//保存配置
void MainWindow::on_btn_saveSetting_clicked()
{
    if(!tbRole->getAllRoleBeans(allRoleBeans)){
        return;
    }

    QString bloodKey = leBloodKey->text();
    if(!DeviceUtils::checkString(bloodKey,"^(F(([1-9])|(10)))?$")){
        tvLog->append("加血键设置错误,范围F1-F10");
        return;
    }

    QString magicKey = leMagicKey->text();
    if(!DeviceUtils::checkString(magicKey,"(^F(([1-9])|(10)))?$")){
        tvLog->append("加蓝键设置错误,范围F1-F10");
        return;
    }


    QString skillKey = leSkill->text();
    if(!DeviceUtils::checkString(skillKey,"^(F(([1-9])|(10)))?$")){
        tvLog->append("无CD技能键设置错误,范围F1-F10");
        return;
    }

    QString skill2Key = leSkill2->text();
    if(!DeviceUtils::checkString(skill2Key,"^(F(([1-9])|(10)))?$")){
        tvLog->append("技能2键设置错误,范围F1-F10");
        return;
    }

    QString speed = leSpeed->text();
    if(!DeviceUtils::checkString(speed,"^(F(([1-9])|(10)))?$")){
        tvLog->append("加速键设置错误,范围F1-F10");
        return;
    }

    QString leImgDiscernStr =leImgDiscern->text();
    if(!DeviceUtils::checkString(leImgDiscernStr,"^(0\\.[89][0-9]{0,2})|1(\\.0{1,2})?$")){
        tvLog->append("设置图片识别率错误,范围0.8-1，精确度:千分位");
        return;
    }

    Setting::getInstance()->setBloodKey(bloodKey);
    Setting::getInstance()->setMagicKey(magicKey);
    Setting::getInstance()->setSkill(skillKey);
    Setting::getInstance()->setSkill2(skill2Key);
    Setting::getInstance()->setSpeed(speed);
    Setting::getInstance()->setImgDiscern(leImgDiscernStr.toFloat());

    if(btnHell_ly->isChecked()){
        Setting::getInstance()->setOutHellCity("luoyang");
    }else if(btnHell_dl->isChecked()){
        Setting::getInstance()->setOutHellCity("dali");
    }else if(btnHell_sz->isChecked()){
        Setting::getInstance()->setOutHellCity("suzhou");
    }else if(btnHell_dhgz->isChecked()){
        Setting::getInstance()->setOutHellCity("dongheguzhen");
    }

    tbRole->saveRoles2File();
    tvLog->append("保存配置成功");
}

void MainWindow::on_pushButton_2_clicked()
{
    tbRole->creatNewRow();
}

void MainWindow::on_pushButton_3_clicked()
{
    runshopTable->creatNewRow();
}

void MainWindow::on_pushButton_4_clicked()
{
    intRunshopData(false);
}

bool MainWindow::intRunshopData(bool isNeedFindPath)
{

    if(!tbRole->getAllRoleBeans(allRoleBeans)){
        return false;
    }

    if(!runshopTable->getAllTableBeans(allRunShopBeans, isNeedFindPath)){
        return false;
    }
    for(RunShopBean *runshopbean : *allRunShopBeans){

        if( runshopbean->num <= 0 || runshopbean->num > allRoleBeans->size()){
            if(QMessageBox::warning(this,"系统提示", "跑商序号需要和角色的序号对应",QMessageBox::Ok)){
                return false;
            }
        }

        RoleBean *role= allRoleBeans->at(runshopbean->num - 1);
        role->runshopBean = runshopbean;
    }
    if(!runshopTable->saveBeans2File()){
        if(QMessageBox::warning(this,"系统提示", "跑商设置保存失败,请看日志",QMessageBox::Ok)){
            return false;
        }
    }
    tvLog->append("跑商设置保存成功");
    return true;
}

bool MainWindow::intKuoZhangData(bool isNeedFindPath)
{
    if(!tbRole->getAllRoleBeans(allRoleBeans)){
        return false;
    }

    if(!kuozhangTable->getAllTableBeans(allKuoZhangBeans, isNeedFindPath)){
        return false;
    }
    for(KuoZhangBean *kuoZhangBean : *allKuoZhangBeans){

        if( kuoZhangBean->num <= 0 || kuoZhangBean->num > allRoleBeans->size()){
            if(QMessageBox::warning(this,"系统提示", "跑商序号需要和角色的序号对应",QMessageBox::Ok)){
                return false;
            }
        }

        RoleBean *role= allRoleBeans->at(kuoZhangBean->num - 1);
        role->kuozhang = kuoZhangBean;
    }
    if(!kuozhangTable->saveBeans2File()){
        if(QMessageBox::warning(this,"系统提示", "扩张任务保存失败,请看日志",QMessageBox::Ok)){
            return false;
        }
    }
    tvLog->append("扩张任务保存成功");
    return true;
}

bool MainWindow::intZhongZhiData()
{
    if(!tbRole->getAllRoleBeans(allRoleBeans)){
        return false;
    }
    if(!zhongZhiTable->getAllTableBeans(allZhongZhiBeans)){
        return false;
    }

    for(ZhongZhiBean *zhongZhiBean : *allZhongZhiBeans){

        if( zhongZhiBean->num <= 0 || zhongZhiBean->num > allZhongZhiBeans->size()){
            if(QMessageBox::warning(this,"系统提示", "角色序号需要和角色的序号对应",QMessageBox::Ok)){
                return false;
            }
        }

         RoleBean *role= allRoleBeans->at(zhongZhiBean->num - 1);
        role->zhongzhi = zhongZhiBean;
    }
    if(!zhongZhiTable->saveBeans2File()){
        if(QMessageBox::warning(this,"系统提示", "种植任务保存失败,请看日志",QMessageBox::Ok)){
            return false;
        }
    }
    tvLog->append("种植任务保存成功");
    return true;
}

/**************************************跑商逻辑**************************************/
void MainWindow::taskRunshop(QPushButton *btn, int runStatue, int taskType)
{
    if(GameManager::getInstantce()->roleTask == ROLE_TASK_NORMAL){
        if(!intRunshopData(true)) return;
        tvLog->clear();
        btn->setText("结束跑商");
        if(runShop == nullptr){
            runShop = new RunShop(this);
            connect(runShop, &RunShop::finish, this,[=](){
                //结束跑商
                setRunshopFinishView(btn, taskType);
            });
        }
        runShop->runStatue = runStatue;
        GameManager::getInstantce()->roleTask = taskType;
        runShop->initData(allRoleBeans);
        Win32Util::setSetWindowPos();
        connect(gameTask, &GameTask::isHell, this, [=](){
            gamePersent->resurgence();
        });

        gameTask->backgroundTask(taskType);
        tvLog->append("开始跑商");
        setButtonEnable(taskType, true);
        qDebug()<< "thread=" <<QThread::currentThreadId();
        threadPool->start(runShop);

    }else{
        cancelTaskRunshop(btn);
    }
}

void MainWindow::setRunshopFinishView(QPushButton* btn, int runType){
    if(btn != nullptr){
        if(runType == ROLE_TASK_SHOP){
            btn->setText("开始跑商");
        }else if(runType == ROLE_TASK_SHOP_REMOTE){
            btn->setText("前往对方");
        }else if(runType == ROLE_TASK_SHOP_BACK){
            btn->setText("前往本帮");
        }

        setButtonEnable(ROLE_TASK_NORMAL,true);
    }
    tvLog->append("跑商结束");
}

void MainWindow::setButtonEnable(int task, bool isEnable)
{
    if(task == ROLE_TASK_SHOP){
        btnRunMerchant->setEnabled(isEnable);
        btnRunRemote->setEnabled(!isEnable);
        btnTaskExpand->setEnabled(!isEnable);
         btnRunGroup->setEnabled(!isEnable);
         btnTaskZhongZhi->setEnabled(!isEnable);
    }else if(task == ROLE_TASK_SHOP_REMOTE){
        btnRunRemote->setEnabled(isEnable);
        btnRunMerchant->setEnabled(!isEnable);
        btnTaskExpand->setEnabled(!isEnable);
         btnRunGroup->setEnabled(!isEnable);
          btnTaskZhongZhi->setEnabled(!isEnable);
    }else if(task == ROLE_TASK_NORMAL){
        btnRunMerchant->setEnabled(isEnable);
        btnRunRemote->setEnabled(isEnable);
         btnRunGroup->setEnabled(isEnable);
        btnTaskExpand->setEnabled(isEnable);
         btnTaskZhongZhi->setEnabled(isEnable);
    }else if(task == ROLE_TASK_SHOP_BACK){
        btnRunMerchant->setEnabled(!isEnable);
        btnRunRemote->setEnabled(!isEnable);
        btnRunGroup->setEnabled(isEnable);
        btnTaskExpand->setEnabled(!isEnable);
         btnTaskZhongZhi->setEnabled(!isEnable);
    }else if(task == ROLE_TASK_ZHONG_ZHI){
        btnTaskZhongZhi->setEnabled(isEnable);
        btnRunMerchant->setEnabled(!isEnable);
        btnRunRemote->setEnabled(!isEnable);
        btnRunGroup->setEnabled(!isEnable);
        btnTaskExpand->setEnabled(!isEnable);
    }
}

void MainWindow::cancelTaskRunshop(QPushButton* btn){
    if( GameManager::getInstantce()->roleTask == ROLE_TASK_NORMAL) return;
    tvLog->append("取消跑商中");
    btn->setText("取消跑商中");
    GameManager::getInstantce()->roleTask = ROLE_TASK_NORMAL;
    btn->setEnabled(false);
    if(runShop != nullptr){
        gameTask->stopTask();
    }
}


/*******************************种植任务***************************************/
void MainWindow::taskZhongZhi()
{
    if(GameManager::getInstantce()->roleTask == ROLE_TASK_NORMAL){
        if(!intZhongZhiData()) return;
        tvLog->clear();
        btnTaskZhongZhi->setText("种植结束");
        if(zhongzhi == nullptr){
            zhongzhi = new ZhongZhi(this);
            connect(zhongzhi, &ZhongZhi::finish, this,[=](){
                setButtonEnable(ROLE_TASK_ZHONG_ZHI, true);
                btnTaskZhongZhi->setText("开始种植");
                tvLog->append("种植结束");
                setButtonEnable(ROLE_TASK_NORMAL, true);
            });
        }
        zhongzhi->initData(allRoleBeans);
        Win32Util::setSetWindowPos();
        connect(gameTask, &GameTask::isHell, this, [=](){
            gamePersent->resurgence();
        });

        gameTask->backgroundTask(ROLE_TASK_ZHONG_ZHI);
        tvLog->append("开始种植");
        qDebug()<< "thread=" <<QThread::currentThreadId();
        threadPool->start(zhongzhi);

    }else{
        cancelTaskZhongZhi();
    }
}

void MainWindow::cancelTaskZhongZhi(){
    if( GameManager::getInstantce()->roleTask == ROLE_TASK_NORMAL) return;
    tvLog->append("取消种植中");
    btnTaskZhongZhi->setText("取消种植中");
    GameManager::getInstantce()->roleTask = ROLE_TASK_NORMAL;
    btnTaskZhongZhi->setEnabled(false);
    if(runShop != nullptr){
        gameTask->stopTask();
    }
}

/*******************************扩张任务***************************************/
void MainWindow::taskKuoZhang()
{
    if(GameManager::getInstantce()->roleTask == ROLE_TASK_NORMAL){
        if(!intKuoZhangData(true)) return;
        tvLog->clear();
        btnTaskExpand->setText("结束扩张");
        if(kuoZhang == nullptr){
            kuoZhang = new KuoZhang(this);
            connect(kuoZhang, &KuoZhang::finish, this,[=](){
                setButtonEnable(ROLE_TASK_KUO_ZHANG, true);
                btnTaskExpand->setText("开始扩张");
                tvLog->append("扩张结束");
                setButtonEnable(ROLE_TASK_NORMAL, true);
            });
        }
        kuoZhang->initData(allRoleBeans);
        Win32Util::setSetWindowPos();
        connect(gameTask, &GameTask::isHell, this, [=](){
            gamePersent->resurgence();
        });

        gameTask->backgroundTask(ROLE_TASK_KUO_ZHANG);
        tvLog->append("开始扩张");
        qDebug()<< "thread=" <<QThread::currentThreadId();
        threadPool->start(kuoZhang);

    }else{
        GameManager::getInstantce()->roleTask = ROLE_TASK_NORMAL;
        cancelTaskKuoZhang();
    }
}

void MainWindow::cancelTaskKuoZhang(){
    if( GameManager::getInstantce()->roleTask == ROLE_TASK_NORMAL) return;
    tvLog->append("取消扩张中");
    btnTaskExpand->setText("取消扩张中");
    GameManager::getInstantce()->roleTask = ROLE_TASK_NORMAL;
    btnTaskExpand->setEnabled(false);
    if(runShop != nullptr){
        gameTask->stopTask();
    }
}

void MainWindow::on_kuozhang_add_clicked()
{
    kuozhangTable->creatNewRow();
}

void MainWindow::on_kuozhang_save_clicked()
{
    intKuoZhangData(false);
}

void MainWindow::on_zhongzhi_add_clicked()
{
    zhongZhiTable->creatNewRow();
}

void MainWindow::on_zhongzhi_save_clicked()
{
    intZhongZhiData();
}
